import {defineConfig, loadEnv} from 'vite'
import path, {resolve} from 'path'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'
import versionUpdate from './src/plugins/versionUpdate'


function pathResolve(dir: string) {
    return resolve(process.cwd(), '.', dir)
}

function timeFormat(time: Date | string | number, cFormat: string) {
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
    let date;
    if (typeof time === "object") {
        date = time;
    } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
        }
        if (typeof time === "number" && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
            value = "0" + value;
        }
        return value || 0;
    });
    return time_str;
}

const vT = timeFormat(new Date(), '{y}{m}{d}.{h}.{i}.{s}')

// @ts-expect-error process is a nodejs global
const host = process.env.TAURI_DEV_HOST;

// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
    const cwdEnv = loadEnv(mode, process.cwd())
    const VITE_DEV_PORT = cwdEnv.VITE_DEV_PORT
    return {
        plugins: [
            vue(),
            AutoImport({
                resolvers: [ElementPlusResolver()],
            }),
            Components({
                resolvers: [ElementPlusResolver({
                        importStyle: "sass"
                    }
                )],
            }),
            ElementPlus({
                useSource: true,
            }),
            versionUpdate(`window.Z_APP_VERSION = '${vT}'`)
        ],
        optimizeDeps: {
            esbuild: true,
        },
        // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
        //
        // 1. prevent vite from obscuring rust errors
        clearScreen: false,
        // 2. tauri expects a fixed port, fail if that port is not available
        server: {
            port: VITE_DEV_PORT,
            strictPort: true,
            host: '0.0.0.0',
            hmr: host
                ? {
                    protocol: "ws",
                    host,
                    port: 1421,
                }
                : undefined,
            watch: {
                // 3. tell vite to ignore watching `src-tauri`
                ignored: ["**/src-tauri/**"],
            },
        },
        resolve: {
            alias: [
                {
                    find: /\/#\//,
                    replacement: pathResolve('types')
                },
                {
                    find: '@',
                    replacement: pathResolve('src')
                },
            ],
            dedupe: ['vue']
        },
        // 重构样式位置 （@/ => ↑ 定义了）
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@use "@/assets/style.scss" as *;`,
                },
            },
        },
        // build: {
        //     // 指定输出路径
        //     outDir: `${vT}.dist`,
        //     // 生成静态资源的存放路径
        //     assetsDir: 'assets',
        //     // 小于此阈值的导入或引用资源将内联为 base64 编码，以避免额外的 http 请求。设置为 0 可以完全禁用此项
        //     assetsInlineLimit: 4096,
        //     // 指定使用哪种混淆器。默认为 Esbuild
        //     minify: 'esbuild',
        //     // 构建后是否生成 source map 文件
        //     sourcemap: false,
        //     // 默认情况下，若 outDir 在 root 目录下，则 Vite 会在构建时清空该目录。
        //     emptyOutDir: true,
        //     rollupOptions: {
        //         input: {
        //             index: resolve(__dirname, 'index.html'),
        //         },
        //     },
        // },
    }
});
